package top.kaoshanji.p1ch03b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.IOException;
import java.nio.file.*;

/**
 * 代码清单 p1ch03b-10：目录监视服务的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/11 16:27
 */
public class WatchableExample01 {

    private static final Logger logger = LogManager.getLogger(WatchableExample01.class);

    public static void main(String[] args) throws IOException, InterruptedException {
        logger.info("...代码清单 p1ch03b-10：目录监视服务的使用示例...");

        WatchService service = FileSystems.getDefault().newWatchService();
        Path path = Paths.get(FileConstant.LOCAL_ROOT_PATH).toAbsolutePath();
        path.register(service, StandardWatchEventKinds.ENTRY_CREATE);

        while (true) {
            WatchKey key = service.take();
            for (WatchEvent<?> event: key.pollEvents()) {

                if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                    Path createdPath = (Path) event.context();

                    Path newPath = path.resolve(createdPath);
                    long size = Files.size(newPath);

                    System.out.println(newPath + " ==> " + size);
                }

            }
            key.reset();
        }
    }

}
